#include once "mud-gui/widgets/Label.bi"

namespace ui

SLOT(drawLabel)

	dim as integer dx, dy
	var fw = len((cast(Label ptr, ref)->text)) * 8 'default font is 8 pixels wide
	var fh = 8
	var half_width = int(ref->width / 2)
	var half_height = int(ref->height / 2)
	var half_fw = int(fw / 2)
	var half_fh = int(fh / 2)

	select case cast(Label ptr, ref)->alignment
	case ui.alignment.topleft
		dx = 1 : dy = 1
	case ui.alignment.topcenter
		dx = 1 + (half_width - half_fw) : dy = 1
	case ui.alignment.topright
		dx = (1 + ref->width) - fw : dy = 1
	case ui.alignment.left
		dx = 1 : dy = 1 + (half_height - half_fh)
	case ui.alignment.right
		dx = (1 + ref->width) - fw : dy = 1 + (half_height - half_fh)
	case ui.alignment.bottomleft
		dx = 1 : dy = ref->y + (ref->height - fh)
	case ui.alignment.bottomcenter
		dx = 1 + (half_width - half_fw) : dy = 1 + (ref->height - fh)
	case ui.alignment.bottomright
		dx = (1 + ref->width) - fw : dy = 1 + (ref->height - fh)
	case else
		dx = 1 + (half_width - half_fw) : dy = 1 + (half_height - half_fh)
	end select

	draw string ref->buffer,(dx,dy), (cast(Label ptr, ref)->text), rgb(0,0,0)

	return 1

ENDSLOT

IMP_PROPERTY( Label, alignment, ui.alignment )

property Label.minimumWidth( ) as integer
	return (BaseObject).minwidth
end property

property Label.setMinimumWidth( byval _t_ as integer )
	(BaseObject).minwidth = _t_
end property

property Label.minimumHeight( ) as integer
	return (BaseObject).minheight
end property

property Label.setMinimumHeight( byval _t_ as integer )
	(BaseObject).minheight = _t_
end property

property Label.text() as string
	return m_text
end property

property Label.setText( byref _str_ as string )
	m_text = _str_
	var e = new _GUI_EVENT_
	e->id = gevent.resize
	resizeEvent( toBaseWidget(@this), e )
	delete e
end property

constructor Label( byval parent as BaseWidget ptr = 0, byref _str_ as string = "" )

	if parent <> 0 then
		if parent->cl <> layout_t.canHaveLayout then ShowError("Label widget must have a valid parent.")
		SetParent(parent)

	end if
	setText = _str_

	(BaseObject).id = ui.widgetids.label
	(BaseObject).cl = layout_t.noLayout
	connectSignal(@this,repaint,label.PaintEvent)
	connectSignal(@this,destroy,label.Destroy)
	connectSignal(@this,resize,label.resizeEvent)

end constructor

STATIC_SLOT(Label.resizeEvent)

	if ref->buffer <> 0 then imagedestroy(ref->buffer)
	ref->buffer = imagecreate( ref->width, ref->height, rgba(&hC9,&hC9,&hC9,&hFF) )
	ref->minwidth = len(cast(Label ptr,ref)->text) * 8
	ref->minheight = 8
	ref->status = drawLabel(ref,e)
	return 0

ENDSLOT

STATIC_SLOT(Label.Destroy)

	cast(Label ptr, ref)->setText = ""

	return 0

ENDSLOT

STATIC_SLOT(Label.PaintEvent)

	if ref->status <> 1 then drawLabel(ref,e)

	put( ref->x, ref->y), ref->buffer, TRANS

	return 0

ENDSLOT

end namespace
